package com.vstyran.radio.managers
{
	import com.vstyran.radio.events.MetaEvent;
	import com.vstyran.radio.vos.MetaData;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.GroupSpecifier;
	import flash.net.NetConnection;
	import flash.net.NetGroup;
	import flash.net.NetStream;
	
	[Event(name="metaReceived", type="com.vstyran.radio.events.MetaEvent")]
	[Event(name="connected", type="flash.events.Event")]
	public class MetaManager extends EventDispatcher
	{
		[Bindable]
		public var info:String="";
		
		public function MetaManager()
		{
			netConnection = new NetConnection();
			netConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			netConnection.connect("rtmfp://p2p.rtmfp.net/57136e5303f28e2972c080aa-44b77705c2ac/");
		}
		
		public var netConnection:NetConnection;
		public var netGroup:NetGroup;
		
		
		public function send(obj:Object):void
		{
			netGroup.post(obj);
		}
		
		protected function log(text:String):void
		{
			info += text + "\n";
		}
		
		protected function netStatusHandler(event:NetStatusEvent):void
		{
			log(event.info.code);
			
			if(event.info.code == "NetConnection.Connect.Success")
			{
				setupStream();
			}
		}
		
		public var peerId:String;
		
		private function setupStream():void
		{
			peerId = netConnection.nearID;
			var groupSpec:GroupSpecifier = new GroupSpecifier("p2pRadioMeta");
			groupSpec.serverChannelEnabled = true;
			groupSpec.multicastEnabled = true;
			groupSpec.postingEnabled = true;
			
			netGroup = new NetGroup(netConnection, groupSpec.groupspecWithAuthorizations());
			netGroup.addEventListener(NetStatusEvent.NET_STATUS, groupStatusHandler);
			
			dispatchEvent(new Event("connected"));
		}
		
		protected function groupStatusHandler(event:NetStatusEvent):void
		{
			if(event.info.code == "NetGroup.Posting.Notify")
			{
				trace(event.info.message)
				var meta:MetaData = new MetaData(event.info.message.peer,event.info.message.trackName,event.info.message.like);
				dispatchEvent(new MetaEvent(MetaEvent.META_RECEIVED, meta));
			}
		}
		
	}
}